#include "ValueItem.h"
#include "ReferenceItem.h"


#include <QDebug>



namespace
{
QString VALUE_FIELD_NAME = "value";
}


ValueItem::ValueItem(AbstractItem* parent) :
    AbstractItem(parent)
{
    d = new Data();
    setData(NameData, "Unknown");
}



ValueItem::ValueItem(const QString& name, AbstractItem* parent) :
    AbstractItem(parent)
{
    d = new Data();
    setData(NameData, name);
}


ValueItem::ValueItem(const ValueItem& other) :
        AbstractItem(other)
{
    d = other.d;
}



int ValueItem::fieldCount() const
{
    return (ValueItem::DataType_LAST - AbstractItem::DataType_FIRST + 1);
}



QString ValueItem::fieldName(const int &field) const
{
    QString name = AbstractItem::fieldName(field);
    if (!name.isEmpty()) return name;

    switch (field)
    {
    case ValueData: return VALUE_FIELD_NAME;
    default:        return QString::null;
    }
}



int ValueItem::field(const QString &field_name) const
{
    int ret = AbstractItem::field(field_name);
    if (ret != AbstractItem::UndefinedData) return ret;

    if (field_name == VALUE_FIELD_NAME) return ValueItem::ValueData;

    return AbstractItem::UndefinedData;
}



QVariant ValueItem::value() const
{
    return data(ValueData);
}



void ValueItem::setValue(const QVariant &value)
{
    setData(ValueData, value);
}

void ValueItem::addReference(ValueItem* otherItem)
{
    if (otherItem == this || IS_REFERENCE(otherItem)) return;

    if (findChildren<ValueItem*>().contains(otherItem)) return;

    if (references().contains(otherItem)) return;

    (void) new ReferenceItem(this, otherItem);
}


QList<ValueItem*> ValueItem::references() const
{
    QList<ValueItem*> ret;
    foreach (ReferenceItem* ref, findChildren<ReferenceItem*>())
    {
        if (ref->parent() != this) continue;

        if (!ref->isValid()) continue;
        ret.append(ref->referencedItem());
    }

    return ret;
}

QVariant ValueItem::customData(const int& field, int role) const
{
    //qDebug() << Q_FUNC_INFO;
    Q_UNUSED(role);

    switch (field)
    {
    case ValueData:
        return d->value;

    }

    return QVariant();
}



void ValueItem::setCustomData(const int & field, const QVariant & data)
{
    switch (field)
    {
    case ValueData:
        if (d->value == data) return;
        d->value = data;
        break;

    default:
        return;
    }

    emit sigDirty();

}




